<?php

declare(strict_types=1);

namespace App\Robot\Service;

use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChRoomBroadcastRecord;
use App\CustHub\Model\ChRoomBroadcastRecordTarget;
use App\Robot\Dto\RobotMsgDto;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use function Hyperf\Collection\data_get;

class SendRobotMessageService
{
    #[Inject]
    protected ChRobotMapper $robotMapper;

    public function handle(array $data)
    {
        $robotId = $data['robot_id'];

        $robotInfo = $this->robotMapper->findById($robotId);
        if(empty($robotInfo) || $robotInfo->login_status != 1){
            if(isset($data['ext'])){
                $ext = $data['ext'];
                $this->extHandel($ext, false, 0,'机器人离线');
            }
            return;
        }

        $msgData = new RobotMsgDto();
        $msgData->setMsgType($data['msg_type'])
            ->setContent($data['content'])
            ->setToId($data['to_id'])
            ->setServerId($robotInfo->server_id)
            ->setFilename($data['file_name'] ?? '')
            ->setUuid($robotInfo->uuid);

        //消息发送服务
        $result = make(\App\Robot\Service\RobotMessageService::class, [$msgData])->sendMessage();
        $status = $result['status'];
        $msg_server_id = $result['msg_server_id'];
        if(isset($data['ext'])){
            $ext = $data['ext'];
            $this->extHandel($ext, $status, $msg_server_id, $result['errorMessage']);
        }
    }

    private function extHandel(array $ext,bool $status, int $msg_server_id,string $errMsg = ''): void
    {
        $type = data_get($ext, 'type');
        //群转播
        if($type == 1){
            $update['status'] = $status ? 1 : 2;
            $update['fail_msg'] = $status ? '' : $errMsg;
            $update['msg_server_id'] = $msg_server_id;
            $update['completed_at'] = Carbon::now();
            ChRoomBroadcastRecordTarget::query()
                ->where('id', $ext['target_id'])
                ->update($update);

            if($ext['is_last']){
                $recordId = $ext['record_id'];
                $recordUpdate =[];
                if($status){
                    $recordUpdate['status'] = 1;
                }else{
                    $exists = ChRoomBroadcastRecordTarget::query()
                        ->where('record_id', $recordId)
                        ->where('status',1)
                        ->exists();
                    $recordUpdate['status'] = $exists ? 1 : 2;
                }
                $recordUpdate['completed_at'] = Carbon::now();
                ChRoomBroadcastRecord::query()
                    ->where('id', $recordId)
                    ->update($recordUpdate);
            }
        }
    }
}